package avicit.im.lantop.basic.companycorrespondence.service.impl;

import avicit.im.lantop.basic.companycorrespondence.service.CompanyCorrespondenceService;
import avicit.im.lantop.common.StringUtil;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.RequestUtil;
import avicit.platform6.core.dao.Paging;
import avicit.platform6.core.jdbc.JdbcAvicit;
import avicit.platform6.core.jdbc.Page;
import avicit.platform6.api.session.SessionHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import reactor.netty.http.server.HttpServerRequest;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @ClassName CompanyCorrespondenceServiceImpl
 * @Description 新旧单位部门对应
 * @Author zcl
 * @Date 2020/9/16 9:56
 */
@Service
public class CompanyCorrespondenceServiceImpl implements CompanyCorrespondenceService {
    @Autowired(required = true)
    private JdbcAvicit jdbcAvicit;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Page<Map<String, Object>> loadCompanyCorrespondence(Paging<Map<String, Object>> page, Map<String, Object> parameter) {
        String orgId = (String) parameter.get("orgId");
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT T.ID,\n");
        sbSql.append("       T.ORG_ID ORGID,\n");
        sbSql.append("       T.CURRENT_DEPT_ID CURRENTDEPTID,\n");
        sbSql.append("       T.CURRENT_DEPT_NAME CURRENTDEPTNAME,\n");
        sbSql.append("       T.COUNTERPART_DEPT_NAME COUNTERPARTDEPTNAME,\n");
        sbSql.append("       SV.ORG_NAME ORGNAME\n");
        sbSql.append("  FROM LANTOP_COMPANY_CORRESPONDENCE T\n");
        sbSql.append("  LEFT JOIN SYS_ORG_V SV\n");
        sbSql.append("    ON SV.ID = T.ORG_ID\n");
        sbSql.append(" WHERE T.ORG_ID = '" + orgId + "' ORDER BY T.CURRENT_DEPT_NAME");
        Page<Map<String, Object>> pageBean = new Page<Map<String, Object>>(page.getPageNo(), page.getPageSize());
        jdbcAvicit.getDatesByPageForMap(pageBean, sbSql.toString(), parameter, null);
        return pageBean;
    }

    @Override
    public void deleteCompanyCorrespondence(String ids) throws Exception {
        Assert.notNull(ids);
        String[] idArray = ids.split(",");
        for (int i = 0; i < idArray.length; ++i) {
            String sql = "delete from LANTOP_COMPANY_CORRESPONDENCE where id = '" + idArray[i] + "'";
            this.jdbcAvicit.getJdbcTemplate().execute(sql);
        }
    }

    @Override
    public void insertCompanyCorrespondence(String orgId, String currentDeptId, String currentDeptName, String counterpartDeptName) throws Exception {
        String id = ComUtil.getId();
        String lastUpdateIp = RequestUtil.getClientIp();
        String name = SessionHelper.getLoginSysUserId(request);
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("INSERT INTO LANTOP_COMPANY_CORRESPONDENCE ");
        sbSql.append("(ID , ORG_ID , CURRENT_DEPT_ID, \n");
        sbSql.append("  CURRENT_DEPT_NAME, COUNTERPART_DEPT_NAME , CREATED_BY , CREATION_DATE , LAST_UPDATED_BY ,\n");
        sbSql.append("  LAST_UPDATE_DATE , LAST_UPDATE_IP , VERSION)");
        sbSql.append("VALUES ( ");
        sbSql.append("'");
        sbSql.append(id);
        sbSql.append("','");
        sbSql.append(orgId);
        sbSql.append("','");
        sbSql.append(currentDeptId);
        sbSql.append("','");
        sbSql.append(currentDeptName);
        sbSql.append("','");
        sbSql.append(counterpartDeptName);
        sbSql.append("','");
        sbSql.append(name);
        sbSql.append("',to_date('");
        sbSql.append(ComUtil.Date2String(new Date()));
        sbSql.append("','yyyy-mm-dd'),'");
        sbSql.append(name);
        sbSql.append("',to_date('");
        sbSql.append(ComUtil.Date2String(new Date()));
        sbSql.append("','yyyy-mm-dd'),'");
        sbSql.append(lastUpdateIp);
        sbSql.append("','0')");
        String sql = sbSql.toString().replace("null", "");
        this.jdbcAvicit.getJdbcTemplate().execute(sql);
    }

    @Override
    public Boolean queryCheckData(String currentDeptId, String counterpartDeptName){
        StringBuffer spSql = new StringBuffer();
        spSql.append("SELECT ID FROM LANTOP_COMPANY_CORRESPONDENCE WHERE CURRENT_DEPT_ID = '"+currentDeptId+"' AND COUNTERPART_DEPT_NAME = '"+counterpartDeptName+"'");
        List<Map<String, Object>> list = this.jdbcAvicit.queryForMap(spSql.toString(), null);
        if(list.size() > 0){
            return true;
        }
        return false;
    }

    @Override
    public Map<String, Object> getDept(String orgId, String orgCode,String inputWord) throws Exception {
        Map<String, Object> result = new HashMap<>();
        String tempOrgCode = orgCode;
        if (orgCode.length() > 16) {
            tempOrgCode = orgCode.substring(orgCode.length() - 16);
        }
        StringBuffer spSql = new StringBuffer();
        spSql.append("SELECT PT.ID, TL.DEPT_NAME FROM SYS_DEPT PT JOIN SYS_DEPT_TL TL ON PT.ID = TL.SYS_DEPT_ID  WHERE PT.PARENT_DEPT_ID='-1' AND PT.ORG_ID='"+orgId+"'");
        if (null != inputWord && !"".equals(inputWord)){
            spSql.append(" AND TL.DEPT_NAME LIKE '%"+inputWord+"%'");
        }
        spSql.append(" ORDER BY TL.DEPT_NAME");
        List<Map<String, Object>> listPt = this.jdbcAvicit.queryForMap(spSql.toString(), null);
        result.put("deptList", listPt);
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT DISTINCT(GDDW) GDDW, GDDW AS GDDWID FROM LANTOP_DATA_V_"+tempOrgCode+" ");
        sbSql.append(" WHERE LANTOP_ARCHIVE_STATUS ='3' ");
        sbSql.append(" AND GDDW NOT IN(SELECT TL.DEPT_NAME FROM SYS_DEPT PT JOIN SYS_DEPT_TL TL " );
        sbSql.append(" ON PT.ID = TL.SYS_DEPT_ID WHERE PT.PARENT_DEPT_ID='-1' AND PT.ORG_ID='"+orgId+"')");
        if (null != inputWord && !"".equals(inputWord)){
            sbSql.append(" AND GDDW LIKE '%"+inputWord+"%'");
        }
        List<Map<String, Object>> listSb = this.jdbcAvicit.queryForMap(sbSql.toString(), null);
        result.put("oldDeptList", listSb);
        return result;
    }

    /**
     * 获取对应部门
     * @param orgId
     * @param counterpartDeptName
     * @return
     * @throws Exception
     */
    public String getCorrespondenceDept(String orgId, String counterpartDeptName) throws Exception{
        String result = "";
        StringBuffer spSql = new StringBuffer();
        spSql.append("select WM_CONCAT(chr(39)||CURRENT_DEPT_NAME||chr(39)) as DEPTNAME from LANTOP_COMPANY_CORRESPONDENCE WHERE ORG_ID ='"+orgId+"' and COUNTERPART_DEPT_NAME = '"+counterpartDeptName+"'");
        List<Map<String, Object>> data = this.jdbcAvicit.queryForMap(spSql.toString(), null);
        if(data.size() > 0){
            for (int i = 0; i < data.size(); i++) {
                String con = String.valueOf(data.get(0).get("DEPTNAME"));
                if(!"null".equals(con) && StringUtil.isNotEmpty(con)){
                    result = con;
                }
            }
        }
        return result;
    }

    /**
     *新增页面，选择现有部门时，需要根据已保存的对应关系，再剔除旧部门中已对应的部门
     * @param newDeptName
     * @param orgId
     * @return
     */
    public Map<String,Object> getOldDept(String inputWord,String newDeptName,String orgId,String orgCode) throws Exception {
        String tempOrgCode = orgCode;
        if (orgCode.length() > 16) {
            tempOrgCode = orgCode.substring(orgCode.length() - 16);
        }
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> listSb = null;
        List<Map<String, Object>> oldList = null;
        StringBuffer sSql = new StringBuffer();
        sSql.append("SELECT DISTINCT(GDDW) GDDW, GDDW AS GDDWID FROM LANTOP_DATA_V_"+tempOrgCode+" ");
        sSql.append(" WHERE LANTOP_ARCHIVE_STATUS ='3' ");
        sSql.append(" AND GDDW NOT IN(SELECT TL.DEPT_NAME FROM SYS_DEPT PT JOIN SYS_DEPT_TL TL " );
        sSql.append(" ON PT.ID = TL.SYS_DEPT_ID WHERE PT.PARENT_DEPT_ID='-1' AND PT.ORG_ID='"+orgId+"')");
        if (null != inputWord && !"".equals(inputWord)){
            sSql.append(" AND GDDW LIKE '%"+inputWord+"%'");
        }
        oldList = this.jdbcAvicit.queryForMap(sSql.toString(), null);
        List<Map<String, Object>> list = new ArrayList<>();
        if(null != newDeptName && !"".equals(newDeptName)) {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("SELECT T.ID,\n");
            sbSql.append("       T.ORG_ID ORGID,\n");
            sbSql.append("       T.CURRENT_DEPT_ID CURRENTDEPTID,\n");
            sbSql.append("       T.CURRENT_DEPT_NAME CURRENTDEPTNAME,\n");
            sbSql.append("       T.COUNTERPART_DEPT_NAME COUNTERPARTDEPTNAME,\n");
            sbSql.append("       SV.ORG_NAME ORGNAME\n");
            sbSql.append("  FROM LANTOP_COMPANY_CORRESPONDENCE T\n");
            sbSql.append("  LEFT JOIN SYS_ORG_V SV\n");
            sbSql.append("    ON SV.ID = T.ORG_ID\n");
            sbSql.append(" WHERE T.ORG_ID = '" + orgId + "' ORDER BY T.CURRENT_DEPT_NAME");
            listSb = this.jdbcAvicit.queryForMap(sbSql.toString(), null);
            if(null!= listSb && listSb.size()>0){
                Set<String> s = new HashSet<>();
                for (Map<String, Object> data:listSb){
                    String newDept = (String) data.get("CURRENTDEPTNAME");
                    if(newDeptName.equals(newDept)){
                        String oldName = (String) data.get("COUNTERPARTDEPTNAME");
                        s.add(oldName);
                    }
                }
                for (Map<String, Object> oldData:oldList){
                    String gddw = (String) oldData.get("GDDW");
                    if(!s.contains(gddw)){
                        list.add(oldData);
                    }
                }
                result.put("oldDeptList", list);
            } else {
                result.put("oldDeptList", oldList);
            }
        } else {
            result.put("oldDeptList", oldList);
        }
        return result;
    }
}
